<template>
  <div class="login">
    <!-- Tab 切换 -->
    <el-tabs v-model="activeTab" @tab-click="handleTabClick" type="border-card">
      <!-- 新增人脸登录Tab -->
      <el-tab-pane label="人脸登录" name="face">
        <el-form class="login-form">
          <h3 class="title">企业智勤通</h3>
          <div class="face-login-container">
            <div class="face-preview">
              <video id="video" width="320" height="240" autoplay></video>
              <canvas id="canvas" width="320" height="240" style="display:none;"></canvas>
              <div v-if="!cameraStarted" class="face-placeholder">
                <i class="el-icon-camera" style="font-size: 30px; color: #909399;"></i>
                <p>请开启摄像头</p>
              </div>
              <div v-if="faceLoading" class="face-loading">
                <i class="el-icon-loading" style="font-size: 48px;"></i>
                <p>正在识别中...</p>
              </div>
            </div>
            <div class="face-controls">
              <div class="face-buttons">
                <el-button
                  type="primary"
                  @click="startCamera"
                  :disabled="cameraStarted"
                  icon="el-icon-video-camera">
                  开启摄像头
                </el-button>
                <el-button
                  type="success"
                  @click="captureFace"
                  :disabled="!cameraStarted || faceLoading"
                  icon="el-icon-camera-solid">
                  拍照登录
                </el-button>
                <el-button
                  type="warning"
                  @click="stopCamera"
                  :disabled="!cameraStarted"
                  icon="el-icon-switch-button">
                  关闭摄像头
                </el-button>
              </div>
              <div class="face-tips" :class="{'face-tips-error': faceError}">
                <i :class="faceTipsIcon"></i> {{ faceTips }}
              </div>
            </div>
          </div>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="账号密码登录" name="account">
        <el-form ref="accountForm" :model="accountForm" :rules="accountRules" class="login-form">
          <h3 class="title">企业智勤通</h3>
          <!-- 表单项 -->
          <el-form-item prop="username">
            <el-input
              v-model="accountForm.username"
              type="text"
              auto-complete="off"
              placeholder="账号"
            >
              <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              v-model="accountForm.password"
              type="password"
              auto-complete="off"
              placeholder="密码"
              @keyup.enter.native="handleLogin"
            >
              <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
            </el-input>
          </el-form-item>
          <el-form-item prop="code" v-if="captchaEnabled">
            <el-input
              v-model="accountForm.code"
              auto-complete="off"
              placeholder="验证码"
              style="width: 63%"
              @keyup.enter.native="handleLogin"
            >
              <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
            </el-input>
            <div class="login-code">
              <img :src="codeUrl" @click="getCode" class="login-code-img"/>
            </div>
          </el-form-item>
          <el-checkbox v-model="accountForm.rememberMe" style="margin:0px 0px 25px 0px;">记住密码</el-checkbox>
          <el-form-item style="width:100%;">
            <el-button
              :loading="loading"
              size="medium"
              type="primary"
              style="width:100%;"
              @click.native.prevent="handleLogin"
            >
              <span v-if="!loading">登 录</span>
              <span v-else>登 录 中...</span>
            </el-button>
            <div style="float: right;" v-if="register">
              <router-link class="link-type" :to="'/register'">立即注册</router-link>
            </div>
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <el-tab-pane label="邮箱登录" name="email">
        <el-form ref="emailForm" :model="emailForm" :rules="emailRules" class="login-form">
          <h3 class="title">企业智勤通</h3>
          <!-- 表单项 -->
          <el-form-item prop="email">
            <el-input
              v-model="emailForm.email"
              type="text"
              placeholder="请输入邮箱"
            >
              <svg-icon slot="prefix" icon-class="email" class="el-input__icon input-icon" />
            </el-input>
          </el-form-item>
          <el-form-item prop="emailCode">
            <el-input
              v-model="emailForm.emailCode"
              auto-complete="off"
              placeholder="请输入验证码"
              style="width: 63%"
            >
              <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
            </el-input>
            <el-button
              type="primary"
              style="float: right; width: 35%;"
              :disabled="emailCodeBtnDisabled"
              @click="getEmailCode"
            >
              {{ emailCodeBtnText }}
            </el-button>
          </el-form-item>
          <el-form-item style="width:100%;">
            <el-button
              :loading="loading"
              size="medium"
              type="primary"
              style="width:100%;"
              @click.native.prevent="handleLogin"
            >
              <span v-if="!loading">登 录</span>
              <span v-else>登 录 中...</span>
            </el-button>
            <div style="float: right;" v-if="register">
              <router-link class="link-type" :to="'/register'">立即注册</router-link>
            </div>
          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>

    <!-- 底部 -->
    <div class="el-login-footer">
      <span>Copyright © 2018-2025 ruoyi.vip All Rights Reserved.</span>
    </div>
  </div>
</template>

<script>
import { getCodeImg, sendEmailCode, faceLogin } from "@/api/login";
import Cookies from "js-cookie";
import { encrypt, decrypt } from '@/utils/jsencrypt'
import {setToken} from "../utils/auth";

export default {
  name: "Login",
  data() {
    return {
      activeTab: "account", // 当前激活的 tab
      codeUrl: "",
      accountForm: {
        username: "", // 账号
        password: "", // 密码
        rememberMe: false,
        code: "", // 验证码
        uuid: "",
        // 新增人脸登录相关数据
        cameraStarted: false,
        mediaStream: null,
        faceLoading: false,
        faceError: false
      },
      faceTips: "请点击开启摄像头",
      emailForm: {
        email: "", // 邮箱
        emailCode: "" // 邮箱验证码
      },
      accountRules: {
        username: [
          { required: true, trigger: "blur", message: "请输入您的账号" }
        ],
        password: [
          { required: true, trigger: "blur", message: "请输入您的密码" }
        ],
        code: [{ required: true, trigger: "change", message: "请输入验证码" }]
      },
      emailRules: {
        email: [
          { required: true, trigger: "blur", message: "请输入您的邮箱" },
          { type: "email", message: "请输入正确的邮箱格式", trigger: "blur" }
        ],
        emailCode: [
          { required: true, trigger: "blur", message: "请输入邮箱验证码" }
        ]
      },
      loading: false,
      captchaEnabled: true,
      register: true,
      redirect: undefined,
      emailCodeBtnDisabled: false, // 获取验证码按钮是否禁用
      emailCodeBtnText: "获取验证码", // 获取验证码按钮文字
      emailCodeCountdown: 60 // 倒计时秒数
    };
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true
    }
  },
  created() {
    this.getCode();
    this.getCookie();
  },
  computed: {
    faceTipsIcon() {
      if (this.faceError) return 'el-icon-error';
      if (this.faceLoading) return 'el-icon-loading';
      return 'el-icon-info';
    }
  },
  methods: {
    // 新增人脸登录相关方法
    startCamera() {
      this.faceTips = "正在开启摄像头...";
      const constraints = { video: { width: 320, height: 240 }, audio: false };
      const video = document.getElementById('video');

      navigator.mediaDevices.getUserMedia(constraints)
        .then(stream => {
          this.mediaStream = stream;
          video.srcObject = stream;
          this.cameraStarted = true;
          this.faceTips = "请正对摄像头，然后点击拍照登录";
        })
        .catch(err => {
          console.error("摄像头开启失败:", err);
          this.faceTips = "摄像头开启失败: " + err.message;
        });
    },

    stopCamera() {
      if (this.mediaStream) {
        this.mediaStream.getTracks().forEach(track => track.stop());
        this.mediaStream = null;
        document.getElementById('video').srcObject = null;
        this.cameraStarted = false;
        this.faceTips = "摄像头已关闭";
      }
    },
    async captureFace() {
      //debugger;
      this.faceTips = "正在识别...";
      const video = document.getElementById('video');
      const canvas = document.getElementById('canvas');
      const ctx = canvas.getContext('2d');

      try {
        // 1. 绘制当前视频帧到 Canvas
        ctx.drawImage(video, 0, 0, 320, 240);
        // 2. 获取 Base64 图像数据
        const imageData = canvas.toDataURL('image/jpeg').split(',')[1]; // 只取数据部分
        console.log("图像数据：",imageData)
        // 3. 调用人脸登录接口
        const response = await faceLogin({ image: imageData });
        console.log(response);
        if (response.code === 200) {
          const token = response.token;
          const user = response.user;

          // 存储Token和用户信息
          this.$store.commit('SET_TOKEN', token);
          this.$store.commit('SET_USER', user);
          setToken(token); // 存储 Token
          // 登录成功后关闭摄像头
          this.stopCamera();
          // 跳转到首页
          this.$router.push({ path: this.redirect || "/" });
        } else {
          this.faceTips = "人脸识别失败: " + response.msg;
        }
      } catch (error) {
        console.error("登录失败:", error);
        this.faceTips = "登录失败，请重试";
        this.stopCamera();
      }
    },
    getCode() {
      getCodeImg().then(res => {
        this.captchaEnabled = res.captchaEnabled === undefined ? true : res.captchaEnabled;
        if (this.captchaEnabled) {
          this.codeUrl = "data:image/gif;base64," + res.img;
          this.accountForm.uuid = res.uuid;
        }
      });
    },
    getCookie() {
      const username = Cookies.get("username");
      const password = Cookies.get("password");
      const rememberMe = Cookies.get('rememberMe')
      this.accountForm = {
        username: username === undefined ? this.accountForm.username : username,
        password: password === undefined ? this.accountForm.password : decrypt(password),
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
      };
    },
    handleLogin() {
      const formRef = this.activeTab === "account" ? "accountForm" : "emailForm";
      this.$refs[formRef].validate(valid => {
        if (valid) {
          this.loading = true;
          if (this.activeTab === "account" && this.accountForm.rememberMe) {
            Cookies.set("username", this.accountForm.username, { expires: 30 });
            Cookies.set("password", encrypt(this.accountForm.password), { expires: 30 });
            Cookies.set('rememberMe', this.accountForm.rememberMe, { expires: 30 });
          } else {
            Cookies.remove("username");
            Cookies.remove("password");
            Cookies.remove('rememberMe');
          }

          // 根据登录方式发送不同的数据
          const loginData = this.activeTab === "account"
            ? { username: this.accountForm.username, password: this.accountForm.password, code: this.accountForm.code, uuid: this.accountForm.uuid }
            : { email: this.emailForm.email, code: this.emailForm.emailCode };

          if (this.activeTab === "account") {
            this.$store.dispatch("Login", loginData).then(() => {
              this.$router.push({ path: "/index" }).catch(() => {});
            }).catch(() => {
              this.loading = false;
              if (this.captchaEnabled) {
                this.getCode();
              }
            });
          } else {
            this.$store.dispatch("EmailLogin", loginData).then(() => {
              this.$router.push({ path: "/index" }).catch(() => {});
            }).catch(() => {
              this.loading = false;
            });
          }
        }
      });
    },
    handleTabClick(tab) {
      // 切换 tab 时清空表单数据
      // this.$refs.accountForm?.resetFields();
      // this.$refs.emailForm?.resetFields();
    },
    getEmailCode() {
      // 校验邮箱格式
      this.$refs.emailForm.validateField("email", errorMessage => {
        if (!errorMessage) {
          // 调用接口发送验证码
          sendEmailCode({ to: this.emailForm.email }).then(() => {
            this.$message.success("验证码已发送，请查收邮箱");
            // 开始倒计时
            this.emailCodeBtnDisabled = true;
            let countdown = this.emailCodeCountdown;
            const timer = setInterval(() => {
              this.emailCodeBtnText = `${countdown} 秒后重试`;
              countdown--;
              if (countdown < 0) {
                clearInterval(timer);
                this.emailCodeBtnText = "获取验证码";
                this.emailCodeBtnDisabled = false;
              }
            }, 1000);
          }).catch(() => {
            this.$message.error("验证码发送失败，请稍后重试");
          });
        }
      });
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss">
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-image: url("../assets/images/login-background.jpg");
  background-size: cover;
}

.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #707070;
}

/* 设置 el-tabs 的样式 */
.el-tabs--border-card {
  border-bottom-left-radius: 10px;
  border-bottom-right-radius: 10px;
  width: 400px;
}

.login-form {
  height: 400px;
  padding: 25px;
  .el-input {
    height: 38px;
    input {
      height: 38px;
    }
  }
  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
  }
}

.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}

.login-code {
  width: 33%;
  height: 38px;
  float: right;
  img {
    cursor: pointer;
    vertical-align: middle;
  }
}

.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}

.login-code-img {
  height: 38px;
}
/* 新增的人脸登录样式 */
.face-login-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;

  .face-preview {
    position: relative;
    width: 360px;
    height: 240px;
    margin-bottom: 20px;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

    video, canvas {
      width: 100%;
      height: 100%;
      object-fit: cover;
      background-color: #f5f7fa;
    }

    .face-placeholder, .face-loading {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      background-color: rgba(245, 247, 250, 0.8);
      color: #909311;

      p {
        margin-top: 10px;
      }
    }
  }

  .face-controls {
    width: 400px;

    .face-buttons {
      display: flex;
      justify-content: center;
      gap: 10px; /* 使用gap替代margin控制间距 */

      .el-button {
        margin: 0 8px;
        min-width: 100px;
      }
    }

    .face-tips {
      padding: 10px;
      text-align: center;
      color: #606266;
      background-color: #f5f7fa;
      border-radius: 4px;
      font-size: 14px;

      i {
        margin-right: 5px;
      }

      &.face-tips-error {
        color: #f56c6c;
        background-color: #fef0f0;
      }
    }
  }
}
</style>
